package com.mh.messengerdemo;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by kelii on 2018/3/9.
 */

public class MessengerService extends Service {

    Messenger mMessenger = new Messenger(new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
                    //收到消息
                    Log.i("得到结果",msg.getData().getString("msg")+"嘿嘿嘿....");
                    //回复消息
                    Messenger client = msg.replyTo;
                    Message message =   Message.obtain(null,2);
                    Bundle bundle = new Bundle();
                    bundle.putString("reply","我已收到消息");
                    message.setData(bundle);
                    try {
                        client.send(message);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }

                    break;
                    default:
                        super.handleMessage(msg);
            }

        }
    });

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
}
